package com.crowdfunding.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.crowdfunding.entity.BackRecordCrowdFunding;
import com.crowdfunding.entity.CrowdFunding;
import com.crowdfunding.entity.RecordCrowdFunding;
import com.crowdfunding.exception.ImageUploadException;
import com.crowdfunding.feign.UploadAdvice;
import com.crowdfunding.mapper.BackRecordCrowdFundingMapper;
import com.crowdfunding.mapper.CrowdFundingMapper;
import com.crowdfunding.mapper.RecordCrowdFundingMapper;
import com.crowdfunding.service.ICrowdFundingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crowdfunding.service.ICrowdfundingImageService;
import com.crowdfunding.util.UUIDUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Service
public class CrowdFundingServiceImpl extends ServiceImpl<CrowdFundingMapper, CrowdFunding> implements ICrowdFundingService {

    @Autowired
    CrowdFundingMapper crowdFundingMapper;

    @Autowired
    BackRecordCrowdFundingMapper backRecordCrowdFundingMapper;

    @Autowired
    RecordCrowdFundingMapper recordCrowdFundingMapper;
//    @Autowired
//    RecordCrowdFundingMapper recordCrowdFundingMapper;

    @Autowired
    UploadAdvice uploadAdvice;

    @Autowired
    ICrowdfundingImageService imageService;

    @Override
    public List<CrowdFunding> getCrowdFundingList() {

        List<CrowdFunding> list=crowdFundingMapper.selectList(null);

        return list;
    }

    @Override
    public void add(CrowdFunding crowdFunding) {
        crowdFundingMapper.insert(crowdFunding);
    }

    @Override
    //开启事物回滚
    @Transactional(rollbackFor = Exception.class)
    public void insertCrowdFunding(CrowdFunding crowdFunding) {
        crowdFunding.setCfId(UUIDUtils.getUUID());
       crowdFundingMapper.insert(crowdFunding);
    }

    @Override
    public CrowdFunding selectById(String cfId){
        return crowdFundingMapper.selectById(cfId);
    }

    @Override
    public  void deleteCrowFunding(String cfId){
        crowdFundingMapper.deleteById(cfId);
    }

    @Override
    public void updateCrowdFunding(CrowdFunding cF){
        crowdFundingMapper.updateById(cF);
    }

    @Override
    //开启事物回滚
    @Transactional(rollbackFor = Exception.class)
    public int addAmount(double cfrAmount,String cfId,String username){
        try {
            int result=-1;
            //查询出原有金额
//        crowdFundingMapper.select(new QueryWrapper<>().select("cf_already_amount"))
//        crowdFundingMapper.updateAmount(cfrAmount,cfId);
            CrowdFunding crowdFunding = crowdFundingMapper.selectOne(new QueryWrapper<CrowdFunding>().eq("cf_id", cfId));
            double Amount=crowdFunding.getCfAlreadyAmount()+cfrAmount;
            System.err.println(Amount);
            //筹款金额超出总金额，提示并进行多余款项退款
            if (Amount>crowdFunding.getCfTotalAmount()){

                RecordCrowdFunding crowdFundin=new RecordCrowdFunding();
                crowdFundin.setCfId(cfId).setUsername(username).setCfrAmount(cfrAmount);
                //添加支付记录
                recordCrowdFundingMapper.insert(crowdFundin);

                //添加退款记录
                double backAmount=Amount-crowdFunding.getCfTotalAmount();
                BackRecordCrowdFunding bkcf=new BackRecordCrowdFunding();
                bkcf.setBCfrAmount(backAmount);
                bkcf.setCfId(cfId);
                bkcf.setUsername(username);
                backRecordCrowdFundingMapper.insert(bkcf);

                //已筹款数额累积,更新数据库
                crowdFunding.setCfAlreadyAmount(Amount-backAmount);
                crowdFundingMapper.updateById(crowdFunding);

                result=2;
            }
            else if(Amount<=crowdFunding.getCfTotalAmount()){
                RecordCrowdFunding crowdFundin=new RecordCrowdFunding();
                crowdFundin.setCfId(cfId).setUsername(username).setCfrAmount(cfrAmount);
                //添加支付记录
                recordCrowdFundingMapper.insert(crowdFundin);

                if (crowdFunding.getCfTotalAmount()==Amount) {
                    crowdFunding.setStatus(2);
                }

                //已筹款数额累积,更新数据库
                crowdFunding.setCfAlreadyAmount(Amount);
                crowdFundingMapper.updateById(crowdFunding);

                result=1;
            }else {
                result=-1;
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }

    }

    @Override
    public CrowdFunding getOneCrowFunding(String cfId){
        return crowdFundingMapper.selectById(cfId);
    }

    @Override
    public void changeCrowdFundingStatus(String cfId, int status){
        CrowdFunding crowdFunding=new CrowdFunding();
        crowdFunding.setStatus(status);
        crowdFundingMapper.update(crowdFunding,
                new UpdateWrapper<CrowdFunding>().eq("cf_id",cfId)
                );
    }

    @Override
    public List<CrowdFunding> getCrowdFundingListByuserName(String username){
        List<CrowdFunding> list = crowdFundingMapper.selectList(new QueryWrapper<CrowdFunding>().eq("username",username));
        return list;
    }

    @Override
    public  List<CrowdFunding> getparticipateList(String username){
        //查询与该用户相关的活动记录
        List<RecordCrowdFunding> recordCrowdFundingList=recordCrowdFundingMapper.selectList(new QueryWrapper<RecordCrowdFunding>().select("cf_id").eq("username",username));
//        System.err.println(recordCrowdFundingList==null);
        //将活动记录中的活动id封装到一个组数中
        if (!recordCrowdFundingList.isEmpty()){
            List<String> cfIdList=new ArrayList<>();
            for (RecordCrowdFunding r: recordCrowdFundingList
            ) {
                cfIdList.add(r.getCfId());
            }
//        cfIdList.forEach(System.err::println);
            //遍历数组查询活动列表
            List<CrowdFunding> crowdFundingList=crowdFundingMapper.selectBatchIds(cfIdList);
//            crowdFundingList.forEach(System.err::println);
            return crowdFundingList;
        }else {
            return null;
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addCrowdFunding(CrowdFunding crowdFunding, MultipartFile[] files) throws Exception {
            String id= UUIDUtils.getUUID();
            crowdFunding.setCfId(id);
            //第一张不为空，则默认文件数组不为空
            if (!files[0].isEmpty()) {
                List<String> urls = new ArrayList<>();
                for (MultipartFile file : files
                ) {
                    urls.add(uploadAdvice.getUrl(file));
                }
//                    设置第一张图片为封面图片
                crowdFunding.setCfImage(urls.get(0));
                // 将所有图片url存库
                imageService.addimages(crowdFunding.getCfId(), urls);
            }else {
                throw new ImageUploadException("图片上传出错");
            }

            crowdFundingMapper.insert(crowdFunding);





    }

}
